package main

import (
	"github.com/gin-gonic/gin"
	newrelic "github.com/newrelic/go-agent"
)

func NewrelicMiddleware(appName string, key string) gin.HandlerFunc {

	if appName == "" || key == "" {
		return func(c *gin.Context) {}
	}

	config := newrelic.NewConfig(appName, key)
	app, err := newrelic.NewApplication(config)

	if err != nil {
		panic(err)
	}

	return func(c *gin.Context) {
		txn := app.StartTransaction(c.Request.URL.Path, c.Writer, c.Request)
		defer txn.End()
		c.Next()
	}
}

func main() {
	r := gin.Default()

	r.Use(NewrelicMiddleware("APP-NAME", "APP-KEY"))

	r.GET("/", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"msg": "hello",
		})
	})
	r.Run(":80")
}
